<template>
	<view class="goods-upload-page">
		<!-- 表单容器 -->
		<view class="form-container">
			<!-- 商品图片上传 -->
			<view class="form-row">
				<view class="form-label">商品图片</view>
				<view class="form-content">
					<!-- <u-upload :max-count="9" @click="console.log('点击')" @success="handleUploadSuccess"
						@error="handleUploadError"
						@delete="handleDeleteImage" :file-list="imageList"
						:auto-upload="true"
						action="http://192.168.0.2:8182/api/boke/v1/item/upload" :show-progress="true" :before-upload="beforeUpload"
						:custom-data="{type: 'goods'}" :header="uploadHeader" multiple>
						<view class="upload-btn">
							<u-icon name="plus" size="24"></u-icon>
							<view class="upload-text">上传图片</view>
						</view>
					</u-upload> -->
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="10"></u-upload>
					<view class="upload-tips">最多上传9张，建议尺寸800×800px</view>
					<view class="error-message" v-if="!validation.flatPatternmakingId.valid">
						{{ validation.flatPatternmakingId.message }}
					</view>
				</view>
			</view>

			<!-- 商品名称 -->
			<view class="form-row">
				<view class="form-label">商品名称</view>
				<view class="form-content">
					<u-input v-model="formData.name" placeholder="请输入商品名称" maxlength="50" @blur="validateName"
						@input="validateName" :class="{'error': !validation.name.valid}"></u-input>
					<view class="error-message" v-if="!validation.name.valid">
						{{ validation.name.message }}
					</view>
				</view>
			</view>

			<!-- 商品分类选择器 -->
			<view class="form-row">
				<view class="form-label">商品分类</view>
				<view class="form-content">
					<picker mode="selector" :range="categoryList" :range-key="'text'" v-model="formData.categoryIdList"
						@change="handleCategoryChange">
						<view class="picker-container">
							<view class="picker-content">
								<text v-if="formData.categoryIdList">
									{{ getCategoryText() }}
								</text>
								<text v-else>{{ getCategoryText() }}</text>
							</view>
							<u-icon name="arrow-right" size="14"></u-icon>
						</view>
					</picker>
					<view class="error-message" v-if="!validation.categoryIdList.valid">
						{{ validation.categoryIdList.message }}
					</view>
				</view>
			</view>
			<!-- 商品厂家选择器 -->
			<view class="form-row">
				<view class="form-label">生产厂家</view>
				<view class="form-content">
					<picker mode="selector" :range="brandList" :range-key="'text'" v-model="formData.manufactureId"
						@change="handlebrandChange">
						<view class="picker-container">
							<view class="picker-content">
								<text v-if="formData.manufactureId">
									{{ getbrandText() }}
								</text>
								<text v-else>{{ getbrandText() }}</text>
							</view>
							<u-icon name="arrow-right" size="14"></u-icon>
						</view>
					</picker>
					<view class="error-message" v-if="!validation.manufactureId.valid">
						{{ validation.manufactureId.message }}
					</view>
				</view>
			</view>
			<!-- 商品价格 -->
			<view class="form-row">
				<view class="form-label">销售价格</view>
				<view class="form-content">
					<u-input v-model="formData.price" placeholder="请输入销售价格" type="digit" maxlength="10"
						@blur="validatePrice" @input="validatePrice"
						:class="{'error': !validation.price.valid}"></u-input>
					<view class="error-message" v-if="!validation.price.valid">
						{{ validation.price.message }}
					</view>
					<view class="form-tips">单位：元</view>
				</view>
			</view>

			<!-- 商品库存 -->
			<!-- <view class="form-row">
				<view class="form-label">商品库存</view>
				<view class="form-content">
					<u-input v-model="formData.stock" placeholder="请输入商品库存" type="digit" maxlength="8"
						@blur="validateStock" @input="validateStock"
						:class="{'error': !validation.stock.valid}"></u-input>
					<view class="error-message" v-if="!validation.stock.valid">
						{{ validation.stock.message }}
					</view>
				</view>
			</view> -->


			<!-- 商品详情 -->
			<view class="form-row">
				<view class="form-label">备注</view>
				<view class="form-content">
					<u-textarea
					      v-model="formData.remark"
					      placeholder="请输入备注信息例如产品详情或介绍等"
					      show-count
					      maxlength="1000"
					      :rows="5"
					    ></u-textarea>
				</view>
			</view>
			<!-- 商品状态 -->
			<view class="form-row">
				<view class="form-label">是否缺货</view>
				<view class="form-content ">
					<u-radio-group v-model="formData.cargo">
						<u-radio class="radio-select" :customStyle="{fontSize:'16px'}"
							v-for="(item, index) in cargoList" :key="index" :label="item.name" :name="item.id"
							@change="radioChange">
						</u-radio>
					</u-radio-group>
				</view>
			</view>
			<!-- 商品状态 -->
			<view class="form-row">
				<view class="form-label">是否新品</view>
				<view class="form-content ">
					<u-radio-group v-model="formData.newProduct">
						<u-radio class="radio-select" :customStyle="{fontSize:'16px'}"
							v-for="(item, index) in radiolist1" :key="index" :label="item.name" :name="item.id"
							@change="radioChange">
						</u-radio>
					</u-radio-group>
				</view>
			</view>
			<!-- 商品状态 -->
			<view class="form-row">
				<view class="form-label">是否热销</view>
				<view class="form-content ">
					<u-radio-group v-model="formData.hotSales">
						<u-radio class="radio-select" :customStyle="{fontSize:'16px'}"
							v-for="(item, index) in hotchangelist" :key="index" :label="item.name" :name="item.id"
							@change="radioChange">
						</u-radio>
					</u-radio-group>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn-container">
			<u-button type="primary" :loading="submitLoading" @click="submitForm">
				提交
			</u-button>
		</view>
	</view>
</template>

<script>
	import request from '../../utils/request';
	import ajax from '../../utils/ajax';
	export default {
		data() {
			return {
				fileList1: [],
				status: '1',
				hotchangelist: [{
						name: '普通',
						id: '0'
					},
					{
						name: '热销',
						id: '1'
					}
				],
				radiolist1: [{
						name: '非新品',
						id: '0'
					},
					{
						name: '新品',
						id: '1'
					}
				],
				cargoList: [
					{
						name: '下架',
						id: '1'
					},{
						name: '上架',
						id: '0'
					}
					
				],
				// 表单数据
				formData: {
					name: '',
					categoryIdList: '', //类别集合
					manufactureId: '', //厂家id集合
					cargo: '0', //是否缺货
					hotSales: '0', //是否热销
					newProduct: '1', //是否新品
					price: '', //销售价格
					vipPrice: '', //会员价
					flatPatternmakingId: [], //商品展示图
					productIntroductionImagesId: [], //商品介绍图
					remark: '', //备注
				},
				// 分类列表
				categoryList: [],
				// 厂家列表
				brandList: [],
				// 上传请求头
				uploadHeader: {
					'Authorization': 'Bearer ' + uni.getStorageSync('token')
				},
				// 提交加载状态
				submitLoading: false,
				// 表单校验状态
				validation: {
					name: {
						valid: true,
						message: '请输入产品名称'
					},
					categoryIdList: {
						valid: true,
						message: ''
					},
					manufactureId: {
						valid: true,
						message: ''
					},
					price: {
						valid: true,
						message: ''
					},
					// stock: {
					// 	valid: true,
					// 	message: ''
					// },
					// remark: {
					// 	valid: true,
					// 	message: ''
					// },
					flatPatternmakingId: {
						valid: true,
						message: ''
					}
				}
			}
		},
		created() {
			this.getProductList()
		},
		methods: {
			deletePic(event) {
				// this[`fileList${event.name}`].splice(event.index, 1);
				console.log(event.file, this.fileList1)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: "http://111.229.46.23:8182/api/boke/v1/item/upload",
						filePath: url,
						name: "image-file",
						formData: {
							type: "1"
						},
						header: {
							'Authorization': 'Bearer' + uni.getStorageSync('token')
						},
						success: (res) => {
							try {
								const responseData = JSON.parse(res.data);
								// console.log('解析后的响应数据:', responseData);

								if (responseData.code == '00000') {
									// 只返回数据，不直接修改 fileList1
									resolve(responseData.data);
								} else {
									reject(new Error(`上传失败: ${responseData.message}`));
								}
							} catch (error) {
								// console.error('解析响应数据失败:', error);
								reject(error);
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;

				// 先添加临时图片（显示上传中状态）
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});

				// 逐个上传并更新状态
				for (let i = 0; i < lists.length; i++) {
					try {
						const result = await this.uploadFilePromise(lists[i].url);
						let item = this[`fileList${event.name}`][fileListLen + i];

						// 更新图片信息（使用服务器返回的真实URL）
						this[`fileList${event.name}`].splice(
							fileListLen + i,
							1,
							Object.assign(item, {
								status: "success",
								message: "",
								url: result.url, // 使用服务器返回的URL
								id: result.id // 添加服务器返回的ID
							})
						);
					} catch (error) {
						// console.error('上传失败:', error);
						// 处理上传失败的情况
						let item = this[`fileList${event.name}`][fileListLen + i];
						this[`fileList${event.name}`].splice(
							fileListLen + i,
							1,
							Object.assign(item, {
								status: "error",
								message: error.message
							})
						);
					}
				}
			},
			//图片上传错误信息
			handleUploadError(e) {
				// console.log(e, '错误信息')
			},
			//获取厂家列表信息
			async getProductList() {
				const result = await request.get('/api/boke/v1/manufacture/list', {}, {});
				const categoryResult = await request.get('/api/boke/v1/category/list', {}, {});
				// console.log(result, 'result')
				// 转换数据格式为Picker所需的选项数组
				this.brandList = result.map(item => ({
					value: item.id,
					text: item.name // 注意：uView Picker默认使用label字段作为显示文本
				}))
				this.categoryList = categoryResult.map(item => ({
					value: item.id,
					text: item.name
				}))

			},
			groupChange(n) {
				// console.log('groupChange', n);
			},
			radioChange(n) {
				// console.log('radioChange', n);
				this.formData.status = n
				console.log(this.formData)
			},
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 图片上传成功
			handleUploadSuccess(e) {
				// console.log(e, '123')
				if (e.statusCode == '00000' && e.data.code === 0) {
					this.imageList.push({
						url: e.data.data.url,
						name: '图片' + (this.imageList.length + 1)
					});
					this.formData.images = this.imageList.map(item => item.url);
				} else {
					uni.$u.toast('图片上传失败，请重试');
				}
			},

			// 删除图片
			handleDeleteImage(index) {
				this.imageList.splice(index, 1);
				this.formData.images = this.imageList.map(item => item.url);
			},

			// 上传前校验
			beforeUpload(file) {
				const size = file.size / 1024 / 1024;
				if (size > 5) {
					uni.$u.toast('图片大小不能超过5MB');
					return false;
				}
				return true;
			},

			handleCategoryChange(e) {
				const index = e.detail.value;
				if (index >= 0 && index < this.categoryList.length) {
					this.formData.categoryIdList = this.categoryList[index].value;
				}

				this.$forceUpdate(); // 强制更新
			},
			//类型选择
			getCategoryText() {
				const category = this.categoryList.find(item => item.value === this.formData.categoryIdList);
				// console.log('5. 查找结果:', category);
				return category ? category.text : '请选择商品分类';
			},
			//厂家选择change事件
			handlebrandChange(e) {
				const index = e.detail.value;
				if (index >= 0 && index < this.brandList.length) {
					this.formData.manufactureId = this.brandList[index].value;
				}
				// console.log(this.formData, 'formdata')
				this.$forceUpdate(); // 强制更新
			},
			//厂家选择
			getbrandText() {
				const brand = this.brandList.find(item => item.value === this.formData.manufactureId);
				return brand ? brand.text : '请选择生产厂家';
				// console.log(brand, '123')
			},
			//测试
			radiocs() {
				// console.log('更新前状态:', this.formData.status);
				this.$nextTick(() => {
					// console.log('更新后状态:', this.formData.status);
				});
			},

			// 校验商品名称
			validateName() {
				if (!this.formData.name.trim()) {
					this.validation.name = {
						valid: false,
						message: '请输入商品名称'
					};
				} else if (this.formData.name.length > 50) {
					this.validation.name = {
						valid: false,
						message: '商品名称不能超过50个字符'
					};
				} else {
					this.validation.name = {
						valid: true,
						message: ''
					};
				}
			},

			// 校验商品分类
			validateCategory() {
				if (!this.formData.categoryIdList) {
					this.validation.categoryIdList = {
						valid: false,
						message: '请选择商品分类'
					};
				} else {
					this.validation.categoryIdList = {
						valid: true,
						message: ''
					};
				}
			},

			// 校验价格
			validatePrice() {
				if (!this.formData.price) {
					this.validation.price = {
						valid: false,
						message: '请输入销售价格'
					};
				} else if (isNaN(Number(this.formData.price)) || Number(this.formData.price) <= 0) {
					this.validation.price = {
						valid: false,
						message: '请输入有效的价格'
					};
				} else {
					this.validation.price = {
						valid: true,
						message: ''
					};
				}
			},

			// 校验库存
			// validateStock() {
			// 	if (!this.formData.stock) {
			// 		this.validation.stock = {
			// 			valid: false,
			// 			message: '请输入商品库存'
			// 		};
			// 	} else if (isNaN(Number(this.formData.stock)) || Number(this.formData.stock) < 0) {
			// 		this.validation.stock = {
			// 			valid: false,
			// 			message: '请输入有效的库存数量'
			// 		};
			// 	} else {
			// 		this.validation.stock = {
			// 			valid: true,
			// 			message: ''
			// 		};
			// 	}
			// },

			// 校验详情
			// validateremark() {
			// 	if (!this.formData.remark.trim()) {
			// 		this.validation.remark = {
			// 			valid: false,
			// 			message: '请输入商品详情'
			// 		};
			// 	} else if (this.formData.remark.length > 1000) {
			// 		this.validation.remark = {
			// 			valid: false,
			// 			message: '商品详情不能超过1000个字符'
			// 		};
			// 	} else {
			// 		this.validation.remark = {
			// 			valid: true,
			// 			message: ''
			// 		};
			// 	}
			// },

			// 校验图片
			validateImages() {
				if (this.formData.flatPatternmakingId.length === 0) {
					this.validation.images = {
						valid: false,
						message: '请上传商品图片'
					};
				} else {
					this.validation.images = {
						valid: true,
						message: ''
					};
				}
			},

			// 提交表单
			async submitForm() {
				// 执行所有校验
				// this.validateName();
				// this.validatePrice();
				// this.validateStock();
				// this.validateremark();
				// this.validateCategory();
				// this.validateImages();
				// 检查是否有任何校验失败
				const isValid = Object.values(this.validation).every(item => item.valid);

				if (!isValid) {
					// 滚动到第一个错误字段
					const firstInvalidField = Object.keys(this.validation).find(key => !this.validation[key].valid);
					if (firstInvalidField) {
						uni.showToast({
							title: this.validation[firstInvalidField].message,
							icon: 'none'
						});
					}
					return;
				}

				// 显示加载状态
				this.submitLoading = true;
				// const pms = {
				// 	name: '',
				// 	categoryIdList: '', //类别集合
				// 	manufactureId: '', //厂家id集合
				// 	cargo: '', //是否缺货
				// 	hotSales: '', //是否热销
				// 	newProduct: '', //是否新品
				// 	price: '', //销售价格
				// 	vipPrice: '', //会员价
				// 	flatPatternmakingId: '', //商品展示图
				// 	productIntroductionImagesId: '', //商品介绍图
				// 	remark: '', //备注
				// }
				console.log(this.fileList1,'this.fileList1')
				this.formData.flatPatternmakingId=this.fileList1.map(item=>item.id)
				this.formData.categoryIdList=[...[this.formData.categoryIdList]]
				console.log(this.formData.flatPatternmakingId,'flatPatternmakingId')
				const result = await ajax.post('/api/boke/v1/item', this.formData, {
					header: {
				        'Authorization': 'Bearer ' + uni.getStorageSync('token')
				      }
					  });
					  // 显示加载状态
					this.submitLoading = false;
						//上传成功处理

				// 模拟提交数据
				// setTimeout(() => {
				// 	console.log('提交商品数据:', this.formData);

				// 	// 模拟API返回
				// 	const success = true;
				console.log(result,'上传成功')
				if(result.code=='00000'){
					uni.$u.toast('商品上传成功')
					this.formData={
					name: '',
					categoryIdList: '', //类别集合
					manufactureId: '', //厂家id集合
					cargo: '1', //是否缺货
					hotSales: '0', //是否热销
					newProduct: '1', //是否新品
					price: '', //销售价格
					vipPrice: '', //会员价
					flatPatternmakingId: [], //商品展示图
					productIntroductionImagesId: [], //商品介绍图
					remark: '', //备注
				}
				this.fileList1=[]
				}else{
					uni.$u.toast(result.msg);
				}
					// if (success) {
					// 	uni.$u.toast('商品上传成功');
					// 	setTimeout(() => {
					// 		uni.navigateBack();
					// 	}, 1500);
				// 	} else {
				// 		uni.$u.toast('商品上传失败，请重试');
				// 	}

				// 	// 隐藏加载状态
				// 	this.submitLoading = false;
				// }, 1500);
			}
		}
	}
</script>

<style lang="scss">
	.u-radio__text {
		font-size: 32rpx !important;
		/* 全局修改，!important 确保优先级 */
		line-height: 32rpx !important;
		padding: 10rpx 0;
		margin-right: 40rpx;
	}

	.goods-upload-page {
		background-color: #f7f8fa;
		min-height: 100vh;

		.form-container {
			background-color: #fff;
			margin-top: 10px;

			.form-row {
				display: flex;
				padding: 16px;
				border-bottom: 1px solid #f2f2f2;

				&:last-child {
					border-bottom: none;
				}

				.form-label {
					width: 90px;
					font-size: 16px;
					color: #333;
					white-space: nowrap;
					margin-right: 15px;
					flex-shrink: 0;
				}

				.form-content {
					flex: 1;

					.u-radio__text {
						font-size: 16px;
					}
				}
			}

			/* 上传区域样式 */
			.upload-btn {
				width: 88px;
				height: 88px;
				border: 1px dashed #e5e5e5;
				border-radius: 8px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				background-color: #f9f9f9;

				.upload-text {
					color: #999;
					font-size: 12px;
					margin-top: 5px;
				}
			}

			.upload-tips {
				color: #999;
				font-size: 12px;
				margin-top: 10px;
			}

			/* 表单提示文字 */
			.form-tips {
				color: #999;
				font-size: 12px;
				margin-top: 5px;
			}

			/* 单选按钮样式 */
			.u-radio-group {
				display: flex;
				align-items: center;
			}

			.u-radio {
				.u-radio__text {
					font-size: 16px;
				}
			}
		}

		/* 上传图片预览样式 */
		.u-upload__preview {
			display: flex;
			flex-wrap: wrap;
			gap: 10px;
			margin-top: 10px;

			.u-upload__item {
				position: relative;
				width: 88px;
				height: 88px;
				border-radius: 6px;
				overflow: hidden;

				.u-upload__delete {
					position: absolute;
					top: 2px;
					right: 2px;
					width: 18px;
					height: 18px;
					border-radius: 50%;
					background-color: rgba(0, 0, 0, 0.6);
					color: #fff;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 10px;
					z-index: 10;
				}
			}
		}

		/* 选择器样式 */
		.picker-container {
			display: flex;
			align-items: center;
			padding: 8px 0;
			width: 100%;
			cursor: pointer;
		}

		.picker-content {
			flex: 1;
			padding-right: 10px;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		/* 错误提示样式 */
		.error-message {
			color: #ff4500;
			font-size: 12px;
			margin-top: 4px;
		}

		/* 错误输入框样式 */
		.u-input__content.error,
		.u-textarea.error {
			border: 1px solid #ff4500;
			border-radius: 4px;
		}

		/* 提交按钮样式 */
		.submit-btn-container {
			padding: 20px 16px;

			.u-button {
				height: 48px;
				border-radius: 8px;
				font-size: 18px;
				background-color: #007aff;
				color: #fff;
			}
		}
		
	}
</style>
